package com.wxd.aspect;

import com.wxd.Exception.RRException;
import com.wxd.annotation.DictFilter;
import com.wxd.modules.sys.entity.SysUserEntity;
import com.wxd.modules.sys.service.SysDeptService;
import com.wxd.modules.sys.service.SysRoleDeptService;
import com.wxd.modules.sys.service.SysUserRoleService;
import com.wxd.modules.sys.shiro.ShiroUtils;
import com.wxd.utils.Constant;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据过滤，切面处理类
 */
@Aspect
@Component
public class DictFilterAspect {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private SysDeptService sysDeptService;
    @Pointcut("@annotation(com.wxd.annotation.DictFilter)")
    public void dictFilterCut()
    {

    }
    @Before("dictFilterCut()")
     public void dictFilter(JoinPoint point)
     {
         Object params = point.getArgs()[0];
         if(params != null && params instanceof Map){
             SysUserEntity user = ShiroUtils.getUserEntity();
             //如果不是超级管理员，则进行数据过滤
             if(user.getUserId() != Constant.SUPER_ADMIN){
                 Map map = (Map)params;
                 //得到当前显示角色Id
                Long roleId = (Long) ShiroUtils.getSession().getAttribute("roleId");
                 map.put(Constant.SQL_FILTER, getSQLFilter(user,roleId, point));
             }
             return ;
         }
         throw new RRException("数据权限接口，只能是Map类型参数，且不能为NULL");
     }
    /**
     *获取数据过滤的SQL
     */
    public String getSQLFilter(SysUserEntity user,Long roleId,JoinPoint point)
    {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DictFilter dictFilter= signature.getMethod().getAnnotation(DictFilter.class);
        //获取表的别名
        String tableAlias = dictFilter.tableAlias();
        if(StringUtils.isNotBlank(tableAlias))
        {
               tableAlias+=".";
        }
        //部门Id列表
        Set<Long> deptIdList=new HashSet<>();
        /*//用户角色对应的部门Id列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if(roleIdList.size()>0)
        {
            List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
            deptIdList.addAll(userDeptIdList);
        }*/
        List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdListByRoleId(roleId);
        deptIdList.addAll(userDeptIdList);
        //得到父部门字典,将父字典也展示出来
        List<Long> allParentIdList = sysDeptService.queryParentIdList(userDeptIdList.get(0));
        deptIdList.addAll(allParentIdList);
        //用户子部门Id列表
        StringBuilder sqlFilter=new StringBuilder();
        sqlFilter.append("(");
        if(deptIdList.size()>0)
        {
            sqlFilter.append(tableAlias).append(dictFilter.deptId()).append(" in(").append(StringUtils.join(deptIdList,",")).append(")");
        }
        //没有本部门数据权限，也能查询本人数据
        if(dictFilter.user()){
            if(deptIdList.size() > 0){
                sqlFilter.append(" or ");
            }
            sqlFilter.append(tableAlias).append(dictFilter.userId()).append("=").append(user.getUserId());
        }
        sqlFilter.append(")");
        if(sqlFilter.toString().trim().equals("()"))
        {
            return null;
        }
        return sqlFilter.toString();
    }
}
